package com.dolphin.controller.admin;


import com.dolphin.base.BaseController;
import com.dolphin.commons.Constants;
import com.dolphin.commons.Pager;
import com.dolphin.commons.ResponseBean;
import com.dolphin.model.Permission;
import com.dolphin.model.ScheduledTask;
import com.dolphin.permission.ApiAuth;
import com.dolphin.service.ScheduledTaskServices;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author nonelonely
 * @date 2020/04/15
 */
@Controller
@RequestMapping("/admin")
public class ScheduledTaskController extends BaseController {

    @Autowired
    private ScheduledTaskServices scheduledTaskServices;


    /**
     * @return java.lang.String
     * @description 定时任务管理页
     * @author dolphin
     */
    @GetMapping("/scheduled")
    @ApiAuth(name = "定时任务管理", groupId = Constants.ADMIN_MENU_GROUP_CONTENT, permission = "admin:scheduled:index")
    public String index() {
        return "/static/admin/pages/scheduled/list.html";
    }

    /**
     * @return java.lang.String
     * @description 添加定时任务
     * @author dolphin
     */
    @GetMapping("/scheduled/addPage")
    @ApiAuth(name = "添加定时任务", type = Permission.ResType.NAV_LINK, permission = "admin:scheduled:addPage")
    public String addScheduledPage() {
        return "/static/admin/pages/scheduled/add.html";
    }

    /**
     * 编辑定时任务
     *
     * @return String
     */
    @GetMapping("/scheduled/editPage/{id}")
    @ApiAuth(name = "编辑定时任务", type = Permission.ResType.NAV_LINK, permission = "admin:scheduled:editPage")
    public String editPage(@PathVariable("id") String id, Model model) {
        ScheduledTask scheduledTask = scheduledTaskServices.getById(Long.parseLong(id));
        model.addAttribute("scheduled", scheduledTask);
        return view("/static/admin/pages/scheduled/edit.html");
    }

    /**
     * 保存添加/修改的数据
     */
    @PostMapping("/scheduled/add")
    @ResponseBody
    @ApiAuth(name = "添加定时任务", permission = "admin:scheduled:add")
    public ResponseBean save(@RequestBody @Valid ScheduledTask scheduledTask) {
        try {
            scheduledTaskServices.saveOrUpdate(scheduledTask);
            return ResponseBean.success("添加成功", scheduledTask);
        } catch (Exception e) {
            return ResponseBean.fail("添加失败", e.getMessage());
        }
    }

    /**
     * 删除定时任务
     *
     * @return String
     */
    @PostMapping("/scheduled/del")
    @ResponseBody
    @ApiAuth(name = "删除定时任务", permission = "admin:scheduled:del")
    public ResponseBean del(@RequestBody String id) {
        if (scheduledTaskServices.removeById(id)) {
            return ResponseBean.success("删除成功", null);
        }
        return ResponseBean.fail("删除失败", null);
    }

    /**
     * 更新定时任务
     *
     * @return String
     */
    @PostMapping("/scheduled/edit")
    @ResponseBody
    @ApiAuth(name = "更新定时任务", permission = "admin:scheduled:edit")
    public ResponseBean editScheduledTask(@RequestBody @Valid ScheduledTask scheduledTask) {
        if (scheduledTaskServices.updateById(scheduledTask)) {
            return ResponseBean.success("更新成功", null);
        }
        return ResponseBean.fail("更新失败", null);
    }

    /**
     * 所有任务列表
     */
    @RequestMapping("/scheduled/list")
    @ResponseBody
    @ApiAuth(name = "所有任务列表(查询)", permission = "admin:scheduled:list")
    public Pager<ScheduledTask> taskList(@RequestBody Pager<ScheduledTask> pager) {
        return scheduledTaskServices.list(pager);
    }

    /**
     * 根据任务key => 启动任务
     */
    @PostMapping("/scheduled/start")
    @ResponseBody
    @ApiAuth(name = "启动任务", permission = "admin:scheduled:start")
    public ResponseBean start(@RequestBody String taskKey) {
        try {
            scheduledTaskServices.start(taskKey);
            return ResponseBean.success("启动成功", taskKey);
        } catch (Exception e) {
            return ResponseBean.fail("启动失败", e.getMessage());
        }


    }

    /**
     * 根据任务key => 停止任务
     */
    @PostMapping("/scheduled/stop")
    @ResponseBody
    @ApiAuth(name = "停止任务", permission = "admin:scheduled:stop")
    public ResponseBean stop(@RequestBody String taskKey) {
        try {
            scheduledTaskServices.stop(taskKey);
            return ResponseBean.success("停止成功", taskKey);
        } catch (Exception e) {
            return ResponseBean.fail("停止失败", e.getMessage());
        }
    }

    /**
     * 根据任务key => 重启任务
     */
    @PostMapping("/scheduled/restart")
    @ResponseBody
    @ApiAuth(name = "重启任务", permission = "admin:scheduled:restart")
    public ResponseBean restart(@RequestBody String taskKey) {
        try {
            scheduledTaskServices.restart(taskKey);
            return ResponseBean.success("成功", taskKey);
        } catch (Exception e) {
            return ResponseBean.fail("失败", e.getMessage());

        }
    }

    /**
     * @param cron     cron表达式
     * @param numTimes 下一(几)次运行的时间
     * @return
     */
    @RequestMapping("/scheduled/getNextExecTime")
    @ResponseBody
    @ApiAuth(name = "cron表达式(查询)", permission = "admin:scheduled:getNextExecTime")
    public ResponseBean getNextExecTime(String cron, Integer numTimes) {
        List<String> list = new ArrayList<>();
        CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
        try {
            cronTriggerImpl.setCronExpression(cron);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 这个是重点，一行代码搞定
        List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, numTimes);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Date date : dates) {
            list.add(dateFormat.format(date));
        }
        return ResponseBean.success("", list);
    }
}
